package com.example.controller;

import com.example.common.Result;
import com.example.domain.Borrow;
import com.example.service.BorrowService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@RestController
public class BorrowController {
    @Autowired
    private BorrowService borrowService;
    @Autowired
    private InformationController informationController;

    /*
    借阅，添加进Borrow表里一条记录
     */
    @GetMapping("/addBorrow")
    public Result addBorrow(@RequestParam Date beginDate,@RequestParam Date endDate,
                            @RequestParam Long userId,@RequestParam Long bookId,@RequestParam String bookName) throws ParseException {
        borrowService.addBorrow(beginDate,endDate, userId, bookId, bookName);
        return Result.success("借阅成功");
    }
    /*
    根据用户id查询借阅的所有记录,查询之前先更新一波借阅状态
     */
    @GetMapping("/selectAllByUserId/{userId}")
    public Result selectAllByUserId(@PathVariable Long userId){
        borrowService.updateStatus(userId);
        List<Borrow> borrows = borrowService.selectAllByUserId(userId);
        return Result.success(borrows);
    }

    @PostMapping("/returnBook")
    public Result returnBook(@RequestBody Borrow borrow){
        Integer downPoints = 0;
        if(borrow.getStatus()==2){
            downPoints = informationController.downPoints(borrow);
        }
        borrowService.returnBook(borrow);
        if(downPoints!=0){
            return Result.warning("逾期还书，已扣除积分"+ downPoints + "，积分为零将不能借书，请及时还书");
        }
        informationController.upPoints(borrow);
        return Result.success("还书成功,增加1积分");
    }
}
